<template>
  <view class="cart-container">
    <!-- 购物车标题 -->
    <view class="cart-header">
      <text class="title">购物车</text>
      <text class="edit-btn" @tap="toggleEdit">{{ isEdit ? '完成' : '编辑' }}</text>
    </view>

    <!-- 购物车列表 -->
    <scroll-view class="cart-list" scroll-y v-if="cartItems.length > 0">
      <view class="cart-item" v-for="(item, index) in cartItems" :key="index">
        <view class="select-box" @tap="toggleSelect(index)">
          <view class="checkbox" :class="{ checked: item.selected }"></view>
        </view>
        <image :src="item.imageUrl || '/static/medicine-default.png'" mode="aspectFill" class="medicine-image"></image>
        <view class="medicine-info">
          <text class="medicine-name">{{ item.medicineName }}</text>
          <text class="medicine-spec">{{ item.specification || '规格信息' }}</text>
          <view class="price-quantity">
            <text class="price">¥{{ item.price }}</text>
            <view class="quantity-control">
              <text class="minus" :class="{ disabled: item.quantity <= 1 }" @tap.stop="decreaseQuantity(index)">-</text>
              <input 
                type="number" 
                v-model="item.quantity" 
                class="quantity-input"
                @input="(e) => handleInputChange(e, index)"
                @blur="(e) => validateQuantity(e, index)"
              />
              <text class="plus" :class="{ disabled: checkStockLimit(item) }" @tap.stop="increaseQuantity(index)">+</text>
            </view>
          </view>
        </view>
        <text class="delete-btn" v-if="isEdit" @tap.stop="removeItem(index)">删除</text>
      </view>
    </scroll-view>

    <!-- 空购物车提示 -->
    <view class="empty-cart" v-else>
      <image src="/static/empty-cart.png" mode="aspectFit" class="empty-image"></image>
      <text class="empty-text">购物车空空如也</text>
      <button class="go-shopping-btn" @tap="goToPharmacy">去选购</button>
    </view>

    <!-- 底部结算栏 -->
    <view class="checkout-bar" v-if="cartItems.length > 0">
      <view class="select-all" @tap="toggleSelectAll">
        <view class="checkbox" :class="{ checked: isAllSelected }"></view>
        <text>全选</text>
      </view>
      <view class="price-info" v-if="!isEdit">
        <view class="total-price">
          <text>合计：</text>
          <text class="price">¥{{ totalPrice }}</text>
        </view>
        <text class="price-desc">不含运费</text>
      </view>
      <button class="checkout-btn" v-if="!isEdit" @tap="goToCheckout" :disabled="selectedCount === 0">
        去结算({{ selectedCount }})
      </button>
      <button class="delete-btn" v-else @tap="deleteSelected" :disabled="selectedCount === 0">
        删除({{ selectedCount }})
      </button>
    </view>
  </view>
</template>

<script>
import { cartApi } from '@/api/cart'

export default {
  data() {
    return {
      cartItems: [],
      isEdit: false,
      isAllSelected: false,
      userId: null,
      isLoading: false
    }
  },
  
  computed: {
    selectedCount() {
      return this.cartItems.filter(item => item.selected).length
    },
    
    totalPrice() {
      return this.cartItems
        .filter(item => item.selected)
        .reduce((total, item) => {
          const price = parseFloat(item.price) || 0
          const quantity = parseInt(item.quantity) || 0
          return total + (price * quantity)
        }, 0)
        .toFixed(2)
    }
  },
  
  onShow() {
    // 获取用户ID并加载购物车数据
    this.userId = this.getUserId()
    if (this.userId) {
      this.loadCartItems()
    }
  },
  
  methods: {
    // 加载购物车数据
    async loadCartItems() {
      if (!this.userId || this.isLoading) return
      
      this.isLoading = true
      uni.showLoading({
        title: '加载中...'
      })
      
      try {
        const res = await cartApi.getCartList(this.userId)
        
        if (res.code === 200 && res.data) {
          // 处理返回的购物车数据
          this.cartItems = res.data.map(item => ({
            ...item,
            selected: false,
            quantity: parseInt(item.quantity) || 1
          }))
          this.updateSelectAllStatus()
        } else {
          throw new Error(res.errorMessage || '获取购物车列表失败')
        }
      } catch (error) {
        console.error('加载购物车数据失败:', error)
        uni.showToast({
          title: '加载购物车数据失败',
          icon: 'none'
        })
      } finally {
        uni.hideLoading()
        this.isLoading = false
      }
    },
    
    // 切换编辑模式
    toggleEdit() {
      this.isEdit = !this.isEdit
    },
    
    // 切换选中状态
    toggleSelect(index) {
      this.cartItems[index].selected = !this.cartItems[index].selected
      this.updateSelectAllStatus()
    },
    
    // 切换全选状态
    toggleSelectAll() {
      this.isAllSelected = !this.isAllSelected
      this.cartItems.forEach(item => {
        item.selected = this.isAllSelected
      })
    },
    
    // 更新全选按钮状态
    updateSelectAllStatus() {
      this.isAllSelected = this.cartItems.length > 0 && this.cartItems.every(item => item.selected)
    },
    
    // 检查库存限制
    checkStockLimit(item) {
      return item.quantity >= (item.minStock || 999)
    },
    
    // 处理数量输入变化
    handleInputChange(e, index) {
      let value = e.detail.value.replace(/[^\d]/g, '')
      let numValue = parseInt(value)
      
      if (isNaN(numValue) || numValue < 1) {
        numValue = 1
      } else if (this.checkStockLimit(this.cartItems[index])) {
        numValue = this.cartItems[index].minStock || 999
        uni.showToast({
          title: `最大可购买数量为${numValue}`,
          icon: 'none'
        })
      }
      
      this.cartItems[index].quantity = numValue
      
      // 防抖更新到后端
      if (this.updateTimer) clearTimeout(this.updateTimer)
      this.updateTimer = setTimeout(() => {
        this.updateCartItemQuantity(index)
      }, 500)
    },
    
    // 验证数量
    validateQuantity(e, index) {
      const item = this.cartItems[index]
      let value = parseInt(item.quantity)
      
      if (isNaN(value) || value < 1) {
        item.quantity = 1
        this.updateCartItemQuantity(index)
      } else if (this.checkStockLimit(item)) {
        item.quantity = item.minStock || 999
        this.updateCartItemQuantity(index)
      }
    },
    
    // 增加商品数量
    async increaseQuantity(index) {
      const item = this.cartItems[index]
      if (this.checkStockLimit(item)) {
        uni.showToast({
          title: `最大可购买数量为${item.minStock || 999}`,
          icon: 'none'
        })
        return
      }
      
      this.cartItems[index].quantity++
      this.updateCartItemQuantity(index)
    },
    
    // 减少商品数量
    async decreaseQuantity(index) {
      const item = this.cartItems[index]
      if (item.quantity <= 1) {
        uni.showToast({
          title: '购买数量不能小于1',
          icon: 'none'
        })
        return
      }
      
      this.cartItems[index].quantity--
      this.updateCartItemQuantity(index)
    },
    
    // 更新购物车项数量到后端
    async updateCartItemQuantity(index) {
      if (this.isLoading) return
      
      const item = this.cartItems[index]
      this.isLoading = true
      
      try {
        const res = await cartApi.updateCartItemQuantity(item.id, item.quantity, this.userId)
        
        if (res.code !== 200) {
          throw new Error(res.errorMessage || '更新数量失败')
        }
      } catch (error) {
        console.error('更新数量失败:', error)
        uni.showToast({
          title: error.message || '更新数量失败',
          icon: 'none'
        })
        
        // 恢复原来的数量（可选）
        this.loadCartItems()
      } finally {
        this.isLoading = false
      }
    },
    
    // 删除单个商品
    async removeItem(index) {
      const item = this.cartItems[index]
      
      uni.showModal({
        title: '提示',
        content: '确定要删除该商品吗？',
        success: async (res) => {
          if (res.confirm) {
            if (this.isLoading) return
            this.isLoading = true
            
            uni.showLoading({
              title: '删除中...'
            })
            
            try {
              const result = await cartApi.deleteCartItem(item.id, this.userId)
              
              if (result.code === 200) {
                this.cartItems.splice(index, 1)
                this.updateSelectAllStatus()
                
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
              } else {
                throw new Error(result.errorMessage || '删除失败')
              }
            } catch (error) {
              console.error('删除商品失败:', error)
              uni.showToast({
                title: error.message || '删除失败',
                icon: 'none'
              })
            } finally {
              uni.hideLoading()
              this.isLoading = false
            }
          }
        }
      })
    },
    
    // 删除选中的商品
    async deleteSelected() {
      if (this.selectedCount === 0 || this.isLoading) return
      
      uni.showModal({
        title: '提示',
        content: `确定要删除选中的${this.selectedCount}件商品吗？`,
        success: async (res) => {
          if (res.confirm) {
            this.isLoading = true
            uni.showLoading({
              title: '删除中...'
            })
            
            try {
              const deletePromises = this.cartItems
                .filter(item => item.selected)
                .map(item => cartApi.deleteCartItem(item.id, this.userId))
              
              const results = await Promise.all(deletePromises)
              
              // 检查是否所有删除操作都成功
              const allSuccess = results.every(res => res.code === 200)
              
              if (allSuccess) {
                // 删除成功后更新购物车
                this.cartItems = this.cartItems.filter(item => !item.selected)
                this.isEdit = false
                this.updateSelectAllStatus()
                
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
              } else {
                throw new Error('部分删除操作失败')
              }
            } catch (error) {
              console.error('批量删除失败:', error)
              uni.showToast({
                title: '删除失败',
                icon: 'none'
              })
              
              // 重新加载购物车
              this.loadCartItems()
            } finally {
              uni.hideLoading()
              this.isLoading = false
            }
          }
        }
      })
    },
    
    // 清空购物车
    async clearCart() {
      if (this.cartItems.length === 0 || this.isLoading) return
      
      uni.showModal({
        title: '提示',
        content: '确定要清空购物车吗？',
        success: async (res) => {
          if (res.confirm) {
            this.isLoading = true
            
            uni.showLoading({
              title: '清空中...'
            })
            
            try {
              const result = await cartApi.clearCart(this.userId)
              
              if (result.code === 200) {
                this.cartItems = []
                this.updateSelectAllStatus()
                
                uni.showToast({
                  title: '购物车已清空',
                  icon: 'success'
                })
              } else {
                throw new Error(result.errorMessage || '清空购物车失败')
              }
            } catch (error) {
              console.error('清空购物车失败:', error)
              uni.showToast({
                title: error.message || '清空购物车失败',
                icon: 'none'
              })
            } finally {
              uni.hideLoading()
              this.isLoading = false
            }
          }
        }
      })
    },
    
    // 跳转到药房页面
    goToPharmacy() {
      uni.switchTab({
        url: '/pages/pharmacy/pharmacy'
      })
    },
    
    // 跳转到结算页面
    goToCheckout() {
      if (this.selectedCount === 0) {
        uni.showToast({
          title: '请选择要结算的商品',
          icon: 'none'
        })
        return
      }
      
      // 将选中的商品信息存储，用于订单确认页面
      const selectedItems = this.cartItems.filter(item => item.selected).map(item => {
        // 确保正确转换为数字
        const price = parseFloat(item.price) || 0;
        // 重要：确保数量正确传递，防止变成默认值1
        const quantity = parseInt(item.quantity) || 1;
        
        console.log(`传递商品: ${item.medicineName}, 数量: ${quantity}, 价格: ${price}`);
        
        return {
          ...item,
          price: price,
          quantity: quantity,
          // 添加单品总价用于调试
          itemTotal: (price * quantity).toFixed(2)
        };
      });
      
      console.log('传递到订单确认页的商品:', JSON.stringify(selectedItems));
      
      // 确保数据正确存储到本地
      try {
        uni.setStorageSync('checkoutItems', selectedItems);
        
        // 验证存储是否成功
        const storedItems = uni.getStorageSync('checkoutItems');
        console.log('已存储的商品数据:', JSON.stringify(storedItems));
        
        uni.navigateTo({
          url: '/pages/pharmacy/order-confirm'
        })
      } catch (e) {
        console.error('存储订单数据失败:', e);
        uni.showToast({
          title: '处理订单数据失败',
          icon: 'none'
        });
      }
    }
  }
}
</script>

<style lang="scss">
.cart-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: 120rpx;
  
  .cart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    background-color: #fff;
    
    .title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .edit-btn {
      font-size: 28rpx;
      color: #666;
    }
  }
  
  .cart-list {
    margin-top: 20rpx;
    max-height: calc(100vh - 240rpx);
    
    .cart-item {
      display: flex;
      align-items: center;
      padding: 30rpx;
      background-color: #fff;
      margin-bottom: 2rpx;
      position: relative;
      
      .select-box {
        margin-right: 20rpx;
        
        .checkbox {
          width: 40rpx;
          height: 40rpx;
          border-radius: 50%;
          border: 2rpx solid #ddd;
          
          &.checked {
            background-color: #ff5500;
            border-color: #ff5500;
            position: relative;
            
            &::after {
              content: '';
              position: absolute;
              top: 50%;
              left: 50%;
              transform: translate(-50%, -50%) rotate(-45deg);
              width: 20rpx;
              height: 10rpx;
              border-left: 4rpx solid #fff;
              border-bottom: 4rpx solid #fff;
            }
          }
        }
      }
      
      .medicine-image {
        width: 160rpx;
        height: 160rpx;
        border-radius: 8rpx;
        margin-right: 20rpx;
      }
      
      .medicine-info {
        flex: 1;
        
        .medicine-name {
          font-size: 28rpx;
          color: #333;
          margin-bottom: 10rpx;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
        }
        
        .medicine-spec {
          font-size: 24rpx;
          color: #999;
          margin-bottom: 20rpx;
        }
        
        .price-quantity {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .price {
            font-size: 32rpx;
            color: #ff5500;
            font-weight: bold;
          }
          
          .quantity-control {
            display: flex;
            align-items: center;
            
            .minus, .plus {
              width: 60rpx;
              height: 60rpx;
              line-height: 56rpx;
              text-align: center;
              border: 1rpx solid #ddd;
              font-size: 36rpx;
            }
            
            .minus {
              border-top-left-radius: 30rpx;
              border-bottom-left-radius: 30rpx;
              color: #999;
            }
            
            .plus {
              border-top-right-radius: 30rpx;
              border-bottom-right-radius: 30rpx;
              color: #333;
            }
            
            .quantity-input {
              text-align: center;
              min-height: 60rpx;
              height: 60rpx;
              line-height: 60rpx;
            }
          }
        }
      }
      
      .delete-btn {
        position: absolute;
        right: 30rpx;
        top: 30rpx;
        font-size: 28rpx;
        color: #ff5500;
      }
    }
  }
  
  .empty-cart {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding-top: 200rpx;
    
    .empty-image {
      width: 240rpx;
      height: 240rpx;
      margin-bottom: 40rpx;
    }
    
    .empty-text {
      font-size: 28rpx;
      color: #999;
      margin-bottom: 60rpx;
    }
    
    .go-shopping-btn {
      width: 300rpx;
      height: 80rpx;
      line-height: 80rpx;
      background-color: #ff5500;
      color: #fff;
      font-size: 28rpx;
      border-radius: 40rpx;
    }
  }
  
  .checkout-bar {
    position: fixed;
    left: 0;
    right: 0;
    bottom: 0;
    height: 100rpx;
    background-color: #fff;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
    
    .select-all {
      display: flex;
      align-items: center;
      
      .checkbox {
        width: 40rpx;
        height: 40rpx;
        border-radius: 50%;
        border: 2rpx solid #ddd;
        margin-right: 20rpx;
        
        &.checked {
          background-color: #ff5500;
          border-color: #ff5500;
          position: relative;
          
          &::after {
            content: '';
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%) rotate(-45deg);
            width: 20rpx;
            height: 10rpx;
            border-left: 4rpx solid #fff;
            border-bottom: 4rpx solid #fff;
          }
        }
      }
      
      text {
        font-size: 28rpx;
        color: #333;
      }
    }
    
    .price-info {
      flex: 1;
      margin-left: 30rpx;
      
      .total-price {
        font-size: 28rpx;
        color: #333;
        
        .price {
          font-size: 36rpx;
          color: #ff5500;
          font-weight: bold;
        }
      }
      
      .price-desc {
        font-size: 24rpx;
        color: #999;
      }
    }
    
    .checkout-btn, .delete-btn {
      width: 240rpx;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      border-radius: 40rpx;
      font-size: 28rpx;
    }
    
    .checkout-btn {
      background-color: #ff5500;
      color: #fff;
      
      &[disabled] {
        background-color: #ccc;
      }
    }
    
    .delete-btn {
      background-color: #ff5500;
      color: #fff;
      
      &[disabled] {
        background-color: #ccc;
      }
    }
  }
}
</style> 